﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Sockets;
using System.Net;
using System.Text;
using UnityEngine.UI;
using System.Threading;

public class ChatManager : MonoBehaviour {
    public string serverIp;
	public int serverPort = 1559;
	private Socket clientSocket;
	public InputField textInput;
    public Text chatText;
    private Thread t;
    private byte[] data=new byte[1024]; //数据容器
    private string message = "";  //消息容器
	// Use this for initialization
	void Start () {
        ConnectToServer();
    }
	
	// Update is called once per frame
	void Update () {
        if (message!=null&& message != "")
        {
            chatText.text += "\n" + message;
            message = "";//清空消息容器
        }
	}

	void ConnectToServer(){
		clientSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        
		clientSocket.Connect(new IPEndPoint(IPAddress.Parse(serverIp),serverPort));

        //创建一个新的线程去接收服务端发来的消息
        t = new Thread(ReceiveMessage);
        t.Start();
	}

    /// <summary>
    /// 这个线程方法用来循环接收消息
    /// </summary>
    void ReceiveMessage()
    {
        while (true)
        {
            if (clientSocket.Connected == false)
                break;
            int length = clientSocket.Receive(data);
            message = Encoding.UTF8.GetString(data, 0, length);
            //chatText.text += "\n"+message;

        }
 

    }

	void SendMessages(string message)
	{
		byte[] resData = Encoding.UTF8.GetBytes(message);
		clientSocket.Send(resData);
	}


	public void OnSendBtnClick(){
		string value = textInput.text;
		SendMessages(value);
        textInput.text = "";
	}

     void OnDestroy()
    {
        clientSocket.Shutdown(SocketShutdown.Both);//断开连接
        clientSocket.Close();//关闭客户端socket
    }
}
